import time
from selenium import webdriver

from novel2.core import Args, down_one_novel

# https://www.wqge.cc/133_133248/
if __name__ == '__main__':
    options = webdriver.ChromeOptions()
    options.headless = True
    driver = webdriver.Chrome(r'../chromedriver', options=options)
    driver.maximize_window()
    target = "https://www.ibiquta.com/read/39507.html"

    try:
        driver.get(target)
        # 获取标题
        title = driver.find_element_by_xpath("//h1|//h2|//h3|//h4").text
        if title == '':
            # 兜底标题
            title = 'novel' + str(time.time()).replace('.','')
            # 获取目录页的容器tag
        cons = driver.find_elements_by_xpath("//dl|//ul")
        container = cons[cons.__len__() - 1]
        maxlen = container.find_elements_by_xpath("//li|//dd").__len__()
        for con in cons:
            cur_len = con.find_elements_by_xpath("//li|//dd").__len__()
            if (cur_len > maxlen):
                container = con
        tag_name = container.tag_name
        all_a = container.find_elements_by_tag_name("a")
        data_list = []
        for a in all_a:
            arg = Args(a.text, a.get_attribute('href'))
            data_list.append(arg)

        one_a = data_list[1].url
        driver.get(one_a)
        # id 中有ontent或class中有个ontent
        contents = driver.find_elements_by_xpath("//div[contains(@id,'ontent')]|//div[contains(@class,'ontent')]")
        content = contents[contents.__len__() - 1]
        content_id = content.get_attribute('id')
        content_class = content.get_attribute('class')
    finally:
        driver.quit()
    save_path = 'D:/小说/'
    # xxx.txt
    title = title + '.txt'
    down_one_novel(target, save_path + title, data_list, content_id, content_class)
